package com.zhj.common.config;

import com.zhj.common.constant.ConfigKey;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import lombok.RequiredArgsConstructor;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
 * 集成knife文档
 */
@Configuration
@EnableOpenApi
@EnableConfigurationProperties(SwaggerProperties.class)
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = ConfigKey.SWAGGER_CONFIG_PREFIX, name = "enable", havingValue = "true")
public class Swagger3AutoConfiguration {

    /** swagger配置 */
    private final SwaggerProperties swaggerProperties;
    /**
     * swagger2的配置文件，这里可以配置swagger2的一些基本的内容，比如扫描的包等等
     *
     * @return the docket
     * @since 1.0.0
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage(this.swaggerProperties.getBasePackage()))
            .paths(PathSelectors.any())
            .build();
    }

    /**
     * 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
     *
     * @return the api info
     * @since 1.0.0
     */
    private ApiInfo apiInfo() {
        String name = this.swaggerProperties.getName();
        String url = this.swaggerProperties.getUrl();
        String email = this.swaggerProperties.getEmail();
        return new ApiInfoBuilder()
            // 页面标题
            .title(this.swaggerProperties.getTitle())
            // 创建人信息
            .contact(new Contact(name, url, email))
            // 版本号
            .version(this.swaggerProperties.getVersion())
            // 描述
            .description(this.swaggerProperties.getDescription())
            .build();
    }
}
